import sys
from PyQt5 import QtCore, QtWidgets
import ui_dlgstd_result
from PyQt5.QtCore import pyqtSlot,pyqtSignal
from PyQt5 import QtSql
import myglobal
from delegates import ComboBoxCompleteDelegate
import os
import getpath
import traceback
import myglobal
import logging
import config_json
# class MyTableView(QtWidgets.QTableView):
#     changed=pyqtSignal()
#     def currentChanged(self,current,previous)

#         super().currentChanged(current,previous)
class DlgStd_result(QtWidgets.QDialog):
    ui=ui_dlgstd_result.Ui_DialogClass();
    def __init__(self, parent=None):
        super().__init__( parent)
        self.ui.setupUi(self)
        self.setWindowTitle("标样结果")
        self.model2 = QtSql.QSqlRelationalTableModel(self);
        self.model2.setTable("method");
        # self.model2.setFilter("methodid="+str(myglobal.methodid));
        self.model2.select();
        self.ui.tableView_method.setModel(self.model2)
        self.ui.tableView_method.setColumnWidth(3, 200);
        self.model = QtSql.QSqlRelationalTableModel(self);
        self.model.setTable("STD_result");
        # self.model.setFilter("methodid="+str(myglobal.methodid));
        # self.model.select();
        self.ui.tableView.setModel(self.model);
        self.ui.tableView.setSortingEnabled(True);
        # self.ui.tableView.contextMenuEvent=self.the_contextMenuEvent
        # self.ui.tableView.customContextMenuRequested.connect(self.the_contextMenuEvent)
        if config_json.setting["complete"]==1:
            std_ids=myglobal.db.get_std_ids()
            self.completer = QtWidgets.QCompleter(std_ids, self)
            self.completer.setFilterMode(QtCore.Qt.MatchContains)
            self.completer.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
            self.completer.setCompletionMode(QtWidgets.QCompleter.UnfilteredPopupCompletion)
            # m_cBoxDelegate.setCompleter(self.completer)
            m_cBoxDelegate=ComboBoxCompleteDelegate(std_ids,self.completer)
            self.ui.tableView.setItemDelegateForColumn(2, m_cBoxDelegate);
        self.ui.tableView.setColumnWidth(2, 200);
        self.ui.tableView_method.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
        self.ui.tableView.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)

        # self.ui.pushButton_add.clicked.connect(self.add_click)
        self.ui.pushButton_from_result.clicked.connect(self.from_result)
        self.ui.pushButton_delete.clicked.connect(self.delete_click)
        self.ui.pushButton_import.clicked.connect(self.import_click)
        self.ui.pushButton_import2.clicked.connect(self.import2_click)
        # self.ui.tableView_method.clicked.connect(self.method_change)#(const QItemSelection &selected, const QItemSelection &deselected)
        # self.ui.tableView_method.currentChanged=self.method_change#(const QModelIndex &current, const QModelIndex &previous)
        # self.ui.tableView_method.setSelectionMode(QtWidgets.QAbstractItemView.SelectionMode.SingleSelection)
        selection_model = self.ui.tableView_method.selectionModel()
        selection_model.currentRowChanged.connect(self.method_change)
        self.ui.pushButton_ok.clicked.connect(self.accept)
        # self.ui.pushButton_ok.setVisible(False)
        self.ui.pushButton_cancel.clicked.connect(self.reject)
        self.ui.pushButton_select_std.clicked.connect(self.pipei)
        self.ui.pushButton_auto.clicked.connect(self.auto_pipei)
        self.ui.pushButton_auto.setVisible(False)
        self.resize(1000,1000)
        self.setCurrent()
    def auto_pipei(self):
        pass
    def setCurrent(self):
        n = self.model2.rowCount()
        if n == 0:
            return
        i=0
        for row in range(n):
            record = self.model2.record(row)
            methodid = record.value(record.indexOf("methodid"))
            logging.info([methodid,myglobal.methodid])
            if methodid==myglobal.methodid:
                break
            i+=1
        self.ui.tableView_method.selectRow(i)
    def contextMenuEvent(self, event):
        menu = QtWidgets.QMenu(self)
        copyAction = menu.addAction("复制标样")
        action = menu.exec_(self.mapToGlobal(event.pos()))
        if action == copyAction:
            self.copySampleid()
    def copySampleid(self):
        selections = self.ui.tableView_method.selectionModel()
        list1 = selections.selectedIndexes()
        ids=[]
        for i in range(len(list1)):
            current = list1[i]
            if current.column() == 0:
                row = current.row()
                record = self.model2.record(row)
                idCol = record.indexOf("methodid")  #
                id1 = record.value(idCol)
                ids.append(id1)
                if len(ids)==2:
                    logging.info(ids)
                    self.copyMethodSampleid(ids)
                    break
        self.model.select()
    def copyMethodSampleid(self,ids):
        [id0,id1]=ids
        if id1<id0:#only copy from low to high
            tmp=id0
            id0=id1
            id1=tmp
        sampleids=myglobal.db.getMethodSampleids(id0)
        ids=myglobal.db.getMethodids(id1)
        i=0
        for one in ids:
            cmd = """update  std_result set sampleid='%s' where id=%d """ % (sampleids[i],one)
            myglobal.db.sql_cmd(cmd)
            i+=1
            if i==len(sampleids):
                break

    def pipei(self):
        from dlgstd import DlgStd
        d = DlgStd()
        r = d.exec_()
        if r==1:
            id1=None
            selections = d.ui.tableView.selectionModel()
            list1 = selections.selectedIndexes()
            for i in range(len(list1)):
                current = list1[i]
                if current.column() == 0:
                    row = current.row()
                    record = d.model.record(row)
                    idCol = record.indexOf("sampleid")  #
                    id1 = record.value(idCol)
            if id1!=None:
                self.setSampleid(id1)
    def setSampleid(self,id1):
        selections = self.ui.tableView.selectionModel()
        list1 = selections.selectedIndexes()
        for i in range(len(list1)):
            current = list1[i]
            if current.column() == 0:
                row = current.row()
                self.model.setData(self.model.index(row,2), id1) #mass
                self.model.submitAll()

                # record = self.model.record(row)
                # idCol = record.indexOf("sampleid")  #
                # id1 = record.value(idCol)
    def method_change(self,current):
        logging.info("method_change")
        # selections = self.ui.tableView_method.selectionModel()
        # list1 = selections.selectedIndexes()
        # for i in range(len(list1)):
        #     current = list1[i]
        row = current.row()
        record = self.model2.record(row)
        idCol = record.indexOf("methodid")  #
        id1 = record.value(idCol)
        # self.ids.remove(id1)
        # if myglobal.methodid==id1:
        #     pass
        # else:
        myglobal.methodid=id1
        self.model.setFilter("methodid="+str(myglobal.methodid));
        self.model.select();
    def import_click(self):
        FileDialog =QtWidgets.QFileDialog(self)
        folder=os.path.join(os.curdir)#os.path.expanduser('~'), "Desktop")
        fil = "xlsx Files (*.xlsx);;All Files (*)"
        FileDirectory = FileDialog.getOpenFileName(
            self, 'select import file', folder, fil)  # 选择目录，返回选中的路径
        fname = FileDirectory[0]
        if fname == "":
            pass
        else:
            try:
                myglobal.methodid=myglobal.db.next_methodid()
                myglobal.db.add_method()
                myglobal.db.import_std_result_file2(fname)
                self.model2.select()
                self.model.setFilter("methodid="+str(myglobal.methodid));
                self.model.select();
            except:
                traceback.print_exc()
    def from_result(self):
        myglobal.methodid=myglobal.db.next_methodid()
        myglobal.db.add_method()
        myglobal.db.from_result()
        self.model2.select()
        self.model.setFilter("methodid="+str(myglobal.methodid));
        self.model.select();
    def import2_click(self):
        FileDialog =QtWidgets.QFileDialog(self)
        folder=os.path.join(os.curdir)#os.path.expanduser('~'), "Desktop")
        fil = "xlsx Files (*.xlsx);;All Files (*)"
        FileDirectory = FileDialog.getOpenFileName(
            self, 'select import file', folder, fil)  # 选择目录，返回选中的路径
        fname = FileDirectory[0]
        if fname == "":
            pass
        else:
            try:
                # myglobal.methodid=myglobal.db.next_methodid()
                myglobal.db.import_std_result_file2(fname)
                self.model.select()
            except:
                traceback.print_exc()
    def add_click(self):
        # myglobal.db.
        self.model.insertRow(0)
        pass
    def delete_click(self):
        myglobal.db.deleteCurrentMethod()
        self.model2.select()
        self.model.setFilter("methodid="+str(myglobal.methodid));
        self.model.select();
    @pyqtSlot()
    def accept(self):
        self.model.submitAll();
        self.done(1)
    @pyqtSlot()    
    def reject(self):
        self.done(0)
if __name__ == "__main__":
    from PyQt5 import QtCore, QtWidgets
    import sys
    a = QtWidgets.QApplication(sys.argv)
    a.lastWindowClosed.connect(a.quit)
    w =Dlgstandard()
    w.show()
    sys.exit(a.exec_())